package com.wuliqing.android.zte.service;

import android.app.Activity;
import android.app.IntentService;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.text.TextUtils;
import android.util.Log;

import com.wuliqing.android.zte.data.ContactData;
import com.wuliqing.android.zte.data.ContactDetailData;

import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;

public class ContactSaveService extends IntentService {
    public static final String ACTION_SET_STARRED = "setStarred";
    public static final String ACTION_DELETE_CONTACT = "delete";
    public static final String EXTRA_CONTACT_URI = "contactUri";
    public static final String EXTRA_STARRED_FLAG = "starred";
    public static final String ACTION_SAVE_CONTACT = "saveContact";
    public static final String EXTRA_UPDATED_PHOTOS = "updatedPhotos";
    public static final String EXTRA_CONTACT_NAME = "contactName";
    public static final String EXTRA_CONTACT_PHONE = "contactPhone";
    public static final String EXTRA_CONTACT_EMAIL = "contactEmail";
    public static final String EXTRA_CONTACT_ADDRESS = "contactAddress";
    public static final String EXTRA_CONTACT_ORGANIZATION = "contactOrganization";
    public static final String EXTRA_CONTACT_NOTE = "contactNote";
    public static final String ACTION_UPDATE_CONTACT = "updateContact";
    public static final String ACTION_UPDATE_CONTACT_PHOTO = "updateContactPhoto";
    public static final String EXTRA_RAW_CONTACT_ID = "contactRawcontactId";
    public static final String EXTRA_CALLBACK_INTENT = "callbackIntent";
    public static final String EXTRA_SAVE_SUCCEEDED = "saveSucceeded";

    private static final String TAG = "WearContactSaveService";

    public interface Listener {
        public void onServiceCompleted(Intent callbackIntent);
    }

    private static final CopyOnWriteArrayList<Listener> sListeners = new CopyOnWriteArrayList<Listener>();

    private Handler mMainHandler;

    public ContactSaveService() {
        super(TAG);
        mMainHandler = new Handler(Looper.getMainLooper());
    }

    public static void registerListener(Listener listener) {
        if (!(listener instanceof Activity)) {
            throw new ClassCastException("Only activities can be registered to"
                    + " receive callback from "
                    + ContactSaveService.class.getName());
        }
        sListeners.add(0, listener);
    }

    public static void unregisterListener(Listener listener) {
        sListeners.remove(listener);
    }

    public void deliverCallback(final Intent callbackIntent) {
        mMainHandler.post(new Runnable() {

            @Override
            public void run() {
                deliverCallbackOnUiThread(callbackIntent);
            }
        });
    }

    void deliverCallbackOnUiThread(final Intent callbackIntent) {
        // TODO: this assumes that if there are multiple instances of the same
        // activity registered, the last one registered is the one waiting for
        // the callback. Validity of this assumption needs to be verified.
        for (Listener listener : sListeners) {
            if (callbackIntent.getComponent().equals(
                    ((Activity) listener).getIntent().getComponent())) {
                listener.onServiceCompleted(callbackIntent);
                return;
            }
        }
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String action = intent.getAction();
        if (ACTION_DELETE_CONTACT.equals(action)) {
            deleteContact(intent);
        } else if (ACTION_SET_STARRED.equals(action)) {
            setStarred(intent);
        } else if (ACTION_SAVE_CONTACT.equals(action)) {
            saveContact(intent);
        } else if (ACTION_UPDATE_CONTACT.equals(action)) {
            updateContact(intent);
        } else if (ACTION_UPDATE_CONTACT_PHOTO.equals(action)) {
            updateContactPhoto(intent);
        }
    }

    public static Intent createUpdateContactPhotoIntent(Context context,
                                                        ContactDetailData contactData,
                                                        Class<? extends Activity> callbackActivity, String callbackAction) {
        Intent serviceIntent = new Intent(context, ContactSaveService.class);
        serviceIntent.setAction(ContactSaveService.ACTION_UPDATE_CONTACT_PHOTO);
        serviceIntent.putExtra(EXTRA_RAW_CONTACT_ID, contactData.getContact_id());
        if (contactData.getPhoto() != null) {
            serviceIntent
                    .putExtra(EXTRA_UPDATED_PHOTOS, contactData.getPhoto());
        }
        if (callbackActivity != null) {
            Intent callbackIntent = new Intent(context, callbackActivity);
            callbackIntent.setAction(callbackAction);
            serviceIntent.putExtra(
                    ContactSaveService.EXTRA_CALLBACK_INTENT,
                    callbackIntent);
        }
        return serviceIntent;
    }

    private void updateContactPhoto(Intent intent) {
        byte[] photo = intent.getByteArrayExtra(EXTRA_UPDATED_PHOTOS);
        long rowContact_id = intent.getLongExtra(EXTRA_RAW_CONTACT_ID, 0);
        boolean succeeded = false;
        if (photo != null) {
            try {
                // update photo
                ContentValues values = new ContentValues();
                values.put(ContactsContract.CommonDataKinds.Photo.PHOTO, photo);
                int isUpdate = getContentResolver()
                        .update(Data.CONTENT_URI,
                                values,
                                Data.RAW_CONTACT_ID + "=?" + " AND "
                                        + Data.MIMETYPE + "=?",
                                new String[]{
                                        String.valueOf(rowContact_id),
                                        ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE});
                if (isUpdate == 0) {
                    values.put(
                            Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
                    values.put(Data.RAW_CONTACT_ID, rowContact_id);
                    getContentResolver().insert(
                            Data.CONTENT_URI, values);
                }
                succeeded = true;
            } catch (Exception e) {
                e.printStackTrace();
                succeeded = false;
            }
        }
        Intent callbackIntent = intent
                .getParcelableExtra(EXTRA_CALLBACK_INTENT);
        if (callbackIntent != null) {
            if (succeeded) {
                // Mark the intent to indicate that the save was successful
                // (even if the lookup URI
                // is now null). For local contacts or the local profile,
                // it's possible that the
                // save triggered removal of the contact, so no lookup URI
                // would exist..
                callbackIntent.putExtra(EXTRA_SAVE_SUCCEEDED, true);
            }
            // callbackIntent.setData(mLookupUri);
            // callbackIntent.putExtra(SAVE_CONTACT_RESULT, result);

            deliverCallback(callbackIntent);
        }
    }

    public static Intent createUpdateContactIntent(Context context,
                                                   ContactDetailData contactData,
                                                   Class<? extends Activity> callbackActivity, String callbackAction) {
        Intent serviceIntent = new Intent(context, ContactSaveService.class);
        serviceIntent.setAction(ContactSaveService.ACTION_UPDATE_CONTACT);
        serviceIntent.putExtra(EXTRA_CONTACT_NAME, contactData.getContact_name());
        serviceIntent.putExtra(EXTRA_CONTACT_PHONE, contactData.getContact_number());
        serviceIntent.putExtra(EXTRA_CONTACT_EMAIL, contactData.getContact_email());
        serviceIntent.putExtra(EXTRA_CONTACT_ADDRESS, contactData.getAddress());
        serviceIntent.putExtra(EXTRA_CONTACT_ORGANIZATION, contactData.getOrganization());
        serviceIntent.putExtra(EXTRA_CONTACT_NOTE, contactData.getNote());
        serviceIntent.putExtra(EXTRA_RAW_CONTACT_ID,
                contactData.getContact_id());
//        if (contactData.getPhoto() != null) {
//            serviceIntent
//                    .putExtra(EXTRA_UPDATED_PHOTOS, contactData.getPhoto());
//        }
        if (callbackActivity != null) {
            Intent callbackIntent = new Intent(context, callbackActivity);
            callbackIntent.setAction(callbackAction);
            serviceIntent.putExtra(
                    ContactSaveService.EXTRA_CALLBACK_INTENT,
                    callbackIntent);
        }
        return serviceIntent;
    }

    private void updateContact(Intent intent) {
        String name = intent.getStringExtra(EXTRA_CONTACT_NAME);
        String phone = intent.getStringExtra(EXTRA_CONTACT_PHONE);
        String email = intent.getStringExtra(EXTRA_CONTACT_EMAIL);
        String address = intent.getStringExtra(EXTRA_CONTACT_ADDRESS);
        String organization = intent.getStringExtra(EXTRA_CONTACT_ORGANIZATION);
        String note = intent.getStringExtra(EXTRA_CONTACT_NOTE);
//        byte[] photo = intent.getByteArrayExtra(EXTRA_UPDATED_PHOTOS);
        long rowContact_id = intent.getLongExtra(EXTRA_RAW_CONTACT_ID, 0);
        boolean succeeded = false;

//        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
        // update phone number
//        if (!TextUtils.isEmpty(phone)) {
//            ops.add(ContentProviderOperation
//                    .newUpdate(Data.CONTENT_URI)
//                    .withSelection(
//                            Data.RAW_CONTACT_ID + "=?" + " AND "
//                                    + Data.MIMETYPE + "=?"
//                                    + " AND " + Phone.TYPE + "=?",
//                            new String[]{String.valueOf(rowContact_id),
//                                    Phone.CONTENT_ITEM_TYPE,
//                                    String.valueOf(Phone.TYPE_MOBILE)})
//                    .withValue(Phone.NUMBER, phone).build());
//        }
        // update name
//        if (!TextUtils.isEmpty(name)) {
//            ops.add(ContentProviderOperation
//                    .newUpdate(Data.CONTENT_URI)
//                    .withSelection(
//                            Data.RAW_CONTACT_ID + "=?" + " AND "
//                                    + Data.MIMETYPE + "=?",
//                            new String[]{String.valueOf(rowContact_id),
//                                    StructuredName.CONTENT_ITEM_TYPE})
//                    .withValue(StructuredName.DISPLAY_NAME, name).build());
//        }
        try {
            //getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
            if (!TextUtils.isEmpty(name)) {
                updateContactName(name, rowContact_id);
            }
            if (!TextUtils.isEmpty(phone)) {
                updateContactPhone(phone, rowContact_id);
            }
            if (!TextUtils.isEmpty(email)) {
                updateContactEmail(email, rowContact_id);
            }
            if (!TextUtils.isEmpty(address)) {
                updateContactAddress(address, rowContact_id);
            }
            if (!TextUtils.isEmpty(note)) {
                updateContactNote(note, rowContact_id);
            }
            if (!TextUtils.isEmpty(organization)){
                updateContactOrganization(organization, rowContact_id);
            }
            succeeded = true;
            Intent callbackIntent = intent
                    .getParcelableExtra(EXTRA_CALLBACK_INTENT);
            if (callbackIntent != null) {
                if (succeeded) {
                    // Mark the intent to indicate that the save was successful
                    // (even if the lookup URI
                    // is now null). For local contacts or the local profile,
                    // it's possible that the
                    // save triggered removal of the contact, so no lookup URI
                    // would exist..
                    callbackIntent.putExtra(EXTRA_SAVE_SUCCEEDED, true);
                }
                // callbackIntent.setData(mLookupUri);
                // callbackIntent.putExtra(SAVE_CONTACT_RESULT, result);

                deliverCallback(callbackIntent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void updateContactName(String name, long rowContact_id) {
        ContentValues values = new ContentValues();
        values.put(StructuredName.DATA1, name);
        int isUpdate = getContentResolver()
                .update(Data.CONTENT_URI,
                        values,
                        Data.RAW_CONTACT_ID + "=?" + " AND "
                                + Data.MIMETYPE + "=?",
                        new String[]{
                                String.valueOf(rowContact_id),
                                StructuredName.CONTENT_ITEM_TYPE});
        if (isUpdate == 0) {
            values.put(Data.RAW_CONTACT_ID, rowContact_id);
            values.put(
                    Data.MIMETYPE,
                    StructuredName.CONTENT_ITEM_TYPE);
            getContentResolver().insert(
                    Data.CONTENT_URI, values);
        }
    }

    private void updateContactPhone(String phone, long rowContact_id) {
        ContentValues values = new ContentValues();
        values.put(Phone.DATA1, phone);
        int isUpdate = getContentResolver()
                .update(Data.CONTENT_URI,
                        values,
                        Data.RAW_CONTACT_ID + "=?" + " AND "
                                + Data.MIMETYPE + "=?"
                                + " AND " + Phone.TYPE + "=?",
                        new String[]{
                                String.valueOf(rowContact_id),
                                Phone.CONTENT_ITEM_TYPE,
                                String.valueOf(Phone.TYPE_MOBILE)});
        if (isUpdate == 0) {
            values.put(Data.RAW_CONTACT_ID, rowContact_id);
            values.put(
                    Data.MIMETYPE,
                    ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
            values.put(
                    ContactsContract.CommonDataKinds.Phone.TYPE,
                    String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE));
            getContentResolver().insert(
                    Data.CONTENT_URI, values);
        }
    }

    private void updateContactOrganization(String organization, long rowContact_id) {
        ContentValues values = new ContentValues();
        values.put(ContactsContract.CommonDataKinds.Organization.DATA1, organization);
        int isUpdate = getContentResolver()
                .update(Data.CONTENT_URI,
                        values,
                        Data.RAW_CONTACT_ID + "=?" + " AND "
                                + Data.MIMETYPE + "=?",
                        new String[]{
                                String.valueOf(rowContact_id),
                                ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE});
        if (isUpdate == 0) {
            values.put(Data.RAW_CONTACT_ID, rowContact_id);
            values.put(
                    Data.MIMETYPE,
                    ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
            getContentResolver().insert(
                    Data.CONTENT_URI, values);
        }
    }

    private void updateContactNote(String note, long rowContact_id) {
        ContentValues values = new ContentValues();
        values.put(ContactsContract.CommonDataKinds.Note.DATA1, note);
        int isUpdate = getContentResolver()
                .update(Data.CONTENT_URI,
                        values,
                        Data.RAW_CONTACT_ID + "=?" + " AND "
                                + Data.MIMETYPE + "=?",
                        new String[]{
                                String.valueOf(rowContact_id),
                                ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE});
        if (isUpdate == 0) {
            values.put(Data.RAW_CONTACT_ID, rowContact_id);
            values.put(
                    Data.MIMETYPE,
                    ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE);
            getContentResolver().insert(
                    Data.CONTENT_URI, values);
        }
    }

    private void updateContactAddress(String address, long rowContact_id) {
        ContentValues values = new ContentValues();
        values.put(ContactsContract.CommonDataKinds.StructuredPostal.DATA1, address);
        int isUpdate = getContentResolver()
                .update(Data.CONTENT_URI,
                        values,
                        Data.RAW_CONTACT_ID + "=?" + " AND "
                                + Data.MIMETYPE + "=?"
                                + " AND " + ContactsContract.CommonDataKinds.StructuredPostal.TYPE + "=?",
                        new String[]{
                                String.valueOf(rowContact_id),
                                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE,
                                String.valueOf(ContactsContract.CommonDataKinds.StructuredPostal.TYPE_HOME)});
        if (isUpdate == 0) {
            values.put(Data.RAW_CONTACT_ID, rowContact_id);
            values.put(
                    Data.MIMETYPE,
                    ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
            values.put(
                    ContactsContract.CommonDataKinds.StructuredPostal.TYPE,
                    String.valueOf(ContactsContract.CommonDataKinds.StructuredPostal.TYPE_HOME));
            getContentResolver().insert(
                    Data.CONTENT_URI, values);
        }
    }

    private void updateContactEmail(String email, long rowContact_id) {
        ContentValues values = new ContentValues();
        values.put(ContactsContract.CommonDataKinds.Email.DATA1, email);
        int isUpdate = getContentResolver()
                .update(Data.CONTENT_URI,
                        values,
                        Data.RAW_CONTACT_ID + "=?" + " AND "
                                + Data.MIMETYPE + "=?"
                                + " AND " + ContactsContract.CommonDataKinds.Email.TYPE + "=?",
                        new String[]{
                                String.valueOf(rowContact_id),
                                ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,
                                String.valueOf(ContactsContract.CommonDataKinds.Email.TYPE_HOME)});
        if (isUpdate == 0) {
            values.put(Data.RAW_CONTACT_ID, rowContact_id);
            values.put(
                    Data.MIMETYPE,
                    ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
            values.put(
                    ContactsContract.CommonDataKinds.Email.TYPE,
                    String.valueOf(ContactsContract.CommonDataKinds.Email.TYPE_HOME));
            getContentResolver().insert(
                    Data.CONTENT_URI, values);
        }
    }

    public static Intent createSaveContactIntent(Context context,
                                                 ContactData contactData,
                                                 Class<? extends Activity> callbackActivity, String callbackAction) {
        Intent serviceIntent = new Intent(context, ContactSaveService.class);
        serviceIntent.setAction(ContactSaveService.ACTION_SAVE_CONTACT);
        serviceIntent.putExtra(EXTRA_CONTACT_NAME, contactData.getContact_name());
        serviceIntent.putExtra(EXTRA_CONTACT_PHONE, contactData.getContact_number());
//		if (contactData.getPhoto() != null) {
//			serviceIntent
//					.putExtra(EXTRA_UPDATED_PHOTOS, contactData.getPhoto());
//		}
//		if (contactData.getStarred_id() != 0) {
//			serviceIntent.putExtra(EXTRA_CONTACT_STARRED_ID,
//					contactData.getStarred_id());
//		}
        if (callbackActivity != null) {
            Intent callbackIntent = new Intent(context, callbackActivity);
            callbackIntent.setAction(callbackAction);
            serviceIntent.putExtra(
                    ContactSaveService.EXTRA_CALLBACK_INTENT,
                    callbackIntent);
        }
        return serviceIntent;
    }

    private long getInsertedRawContactId(
            final ArrayList<ContentProviderOperation> diff,
            final ContentProviderResult[] results) {
        final int diffSize = diff.size();
        for (int i = 0; i < diffSize; i++) {
            ContentProviderOperation operation = diff.get(i);
            if (operation.getUri().getEncodedPath()
                    .contains(RawContacts.CONTENT_URI.getEncodedPath())) {
                return ContentUris.parseId(results[i].uri);
            }
        }
        return -1;
    }

    private void saveContact(Intent intent) {
        String name = intent.getStringExtra(EXTRA_CONTACT_NAME);
        String phone = intent.getStringExtra(EXTRA_CONTACT_PHONE);
        byte[] photo = intent.getByteArrayExtra(EXTRA_UPDATED_PHOTOS);
        boolean succeeded = false;

        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
        ops.add(ContentProviderOperation
                .newInsert(RawContacts.CONTENT_URI)
                .withValue(RawContacts.ACCOUNT_TYPE, null)
                        // .withValue(ContactsContract.RawContacts._ID, 0)
                .withValue(RawContacts.ACCOUNT_NAME, null)
                .withValue(RawContacts.AGGREGATION_MODE,
                        RawContacts.AGGREGATION_MODE_DISABLED)
                .build());
        // add name
        if (!TextUtils.isEmpty(name)) {
            ops.add(ContentProviderOperation
                    .newInsert(Data.CONTENT_URI)
                    .withValueBackReference(
                            Data.RAW_CONTACT_ID, 0)
                    .withValue(
                            Data.MIMETYPE,
                            StructuredName.CONTENT_ITEM_TYPE)
                    .withValue(
                            StructuredName.DISPLAY_NAME,
                            name).build());
        }
        // add phone
        if (!TextUtils.isEmpty(phone)) {
            ops.add(ContentProviderOperation
                    .newInsert(Data.CONTENT_URI)
                    .withValueBackReference(
                            Data.RAW_CONTACT_ID, 0)
                    .withValue(
                            Data.MIMETYPE,
                            Phone.CONTENT_ITEM_TYPE)
                    .withValue(Phone.NUMBER,
                            phone)
                    .withValue(Phone.TYPE,
                            Phone.TYPE_MOBILE).build());
        }
        // add photo

        if (null != photo) {
            ops.add(ContentProviderOperation
                    .newInsert(Data.CONTENT_URI)
                    .withValueBackReference(Data.RAW_CONTACT_ID, 0)
                    .withValue(
                            Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, photo)
                    .build());
        }

        try {
            ContentProviderResult[] results = getContentResolver().applyBatch(
                    ContactsContract.AUTHORITY, ops);
            final long rawContactId = getInsertedRawContactId(ops, results);
            Uri mLookupUri = null;
            final Uri rawContactUri = ContentUris.withAppendedId(
                    RawContacts.CONTENT_URI, rawContactId);
            mLookupUri = RawContacts.getContactLookupUri(getContentResolver(),
                    rawContactUri);
            succeeded = true;
            Intent callbackIntent = intent
                    .getParcelableExtra(EXTRA_CALLBACK_INTENT);
            if (callbackIntent != null) {
                if (succeeded) {
                    // Mark the intent to indicate that the save was successful
                    // (even if the lookup URI
                    // is now null). For local contacts or the local profile,
                    // it's possible that the
                    // save triggered removal of the contact, so no lookup URI
                    // would exist..
                    callbackIntent.putExtra(EXTRA_SAVE_SUCCEEDED, true);
                }
                callbackIntent.setData(mLookupUri);
                // callbackIntent.putExtra(SAVE_CONTACT_RESULT, result);

                deliverCallback(callbackIntent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Creates an intent that can be sent to this service to delete a contact.
     */
    public static Intent createDeleteContactIntent(Context context,
                                                   Uri contactUri, Class<? extends Activity> callbackActivity,
                                                   String callbackAction) {
        Intent serviceIntent = new Intent(context, ContactSaveService.class);
        serviceIntent.setAction(ContactSaveService.ACTION_DELETE_CONTACT);
        serviceIntent.putExtra(ContactSaveService.EXTRA_CONTACT_URI,
                contactUri);
        if (callbackActivity != null) {
            Intent callbackIntent = new Intent(context, callbackActivity);
            callbackIntent.setAction(callbackAction);
            serviceIntent.putExtra(
                    ContactSaveService.EXTRA_CALLBACK_INTENT,
                    callbackIntent);
        }
        return serviceIntent;
    }

    private void deleteContact(Intent intent) {
        Uri contactUri = intent.getParcelableExtra(EXTRA_CONTACT_URI);
        if (contactUri == null) {
            Log.e(TAG, "Invalid arguments for deleteContact request");
            return;
        }

        getContentResolver().delete(contactUri, null, null);
    }

    /**
     * Creates an intent that can be sent to this service to star or un-star a
     * contact.
     */
    public static Intent createSetStarredIntent(Context context,
                                                Uri contactUri, int value) {
        Intent serviceIntent = new Intent(context, ContactSaveService.class);
        serviceIntent.setAction(ContactSaveService.ACTION_SET_STARRED);
        serviceIntent.putExtra(ContactSaveService.EXTRA_CONTACT_URI,
                contactUri);
        serviceIntent
                .putExtra(ContactSaveService.EXTRA_STARRED_FLAG, value);

        return serviceIntent;
    }

    private void setStarred(Intent intent) {
        Uri contactUri = intent.getParcelableExtra(EXTRA_CONTACT_URI);
        int value = intent.getIntExtra(EXTRA_STARRED_FLAG, 0);
        if (contactUri == null) {
            Log.e(TAG, "Invalid arguments for setStarred request");
            return;
        }

        final ContentValues values = new ContentValues(1);
        values.put(Contacts.STARRED, value);
        getContentResolver().update(contactUri, values, null, null);
    }
}
